﻿package aidn.animation.model
{
	import flash.display.Shape;
	import flash.events.Event;
	import flash.filters.BlurFilter;
	import flash.filters.GlowFilter;

	/**
	 * 雪単体
	 */
	public class Snow extends Shape 
	{
		private var _stw :int;
		private var _sth :int;
		
		private var _windSpeed :int;
		private var _dropSpeed :int;
		private var _time      :int;
		
		private var _isDown :Boolean;
		
		/**
		 * 
		 * @param	stw		stageWidth
		 * @param	sth		stageHeight
		 * @param	isDown	落下方向(true:下向き)。
		 */
		public function Snow ( stw:uint = 320, sth:uint = 240, isDown :Boolean = true ) 
		{
			_stw = stw;
			_sth = sth;
			
			_isDown = isDown;
			
			_windSpeed = 2;
			_dropSpeed = Math.round( Math.random() * Math.random() * 15 ) + 2;
			if (! isDown) _dropSpeed = - _dropSpeed;
			
			_time      = Math.random() * 2 - 1;
			
			_init();
		}
		
		/**
		 * ステージサイズをセットします。
		 * @param	stw		stageWidth
		 * @param	sth		stageHeight
		 */
		public function setStageSize ( stw :uint, sth :uint ) :void 
		{
			_stw = stw;
			_sth = sth;
		}
		
		private function _init() :void
		{
			var col :uint = 255 - Math.random() * 110;
			
			graphics.beginFill( col + (col << 8) + (col << 16) );
			graphics.drawCircle( 0, 0, 2 + _abs(_dropSpeed)/3 );
			graphics.endFill();
			
			filters = [ new BlurFilter( 2, _abs(_dropSpeed), 1 ) ];
			addEventListener( Event.ENTER_FRAME, _update ); 
			_reset();
		}
		private function _reset( ) :void 
		{
			x =   _stw * (Math.random() * 2 - 1);
			y = - _sth *  Math.random();
			if ( ! _isDown ) y += (_sth * 2);
			
			scaleX = scaleY = 0.25 + (Math.random() * Math.random() * 0.75);
		}
		private function _update ( evt :Event ) :void 
		{
			y += _dropSpeed;
			x += _windSpeed + Math.sin(_time) * (4 / _abs(_dropSpeed));
			
			if ( _isDown )	{ if ( _sth < y )	_reset(); }
			else			{ if ( y < 0 )		_reset(); }
			
			_time += 0.1;
		}
		
		private function _abs( n :Number ) :Number
		{
			if (n < 0) return -n;
			return n;
		}
		
	}
}

